package com.czh.springboot04.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
// 生成验证码工具类
public class CaptchaUtil {

    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int FONT_SIZE = 20;

    public static String generateCaptcha() {
        Random random = new Random();
        int num1 = random.nextInt(20);
        int num2 = random.nextInt(20);
        int operator = random.nextInt(2);
        char op;
        int result;
        if (operator == 0) {
            op = '+';
            result = num1 + num2;
        } else {
            op = '-';
            result = num1 - num2;
        }
        String question = num1 + " " + op + " " + num2 + " = ?";
        return question + "&" + result;
    }

    public static byte[] createCaptchaImage(String question) throws IOException {
        // 生成随机浅色背景
        Random random = new Random();
        int r = 200 + random.nextInt(56); // 200 - 255
        int g = 200 + random.nextInt(56); // 200 - 255
        int b = 200 + random.nextInt(56); // 200 - 255
        Color bgColor = new Color(r, g, b);

        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 设置背景色
        g2d.setColor(bgColor);
        g2d.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制边框
        g2d.setColor(Color.GRAY);
        g2d.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);

        // 设置字体和颜色
        g2d.setFont(new Font("Arial", Font.BOLD, FONT_SIZE));
        g2d.setColor(Color.BLACK);
        g2d.drawString(question, 20, 30);

        g2d.dispose();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        return baos.toByteArray();
    }
}
